package luafrontend.values;

import java.util.HashMap;
import java.util.Map;

import luafrontend.exceptions.ConversionException;

public class LuaTable extends LuaValue {
	private final Map<LuaValue, LuaValue> vals;
	int counter;
	
	public LuaTable() {
		vals = new HashMap<LuaValue, LuaValue>();
	}
	
	public int getSize() {
		return vals.size();
	}
	
	public void set(LuaValue key, LuaValue value) {
		if (value.isNil()) {
			vals.remove(key);
		}
		else {
			vals.put(key, value);
		}
	}
	
	public LuaValue get(LuaValue key) {
		LuaValue value = vals.get(key);
		
		if (value == null) {
			return new LuaNil();
		}
		else {
			return value;
		}
	}
	
	public void add(LuaValue value) {
		vals.put(new LuaNumber(++counter), value);
	}
	
	public LuaTable asTable() throws ConversionException {
		return this;
	}
	
	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer("table { ");
		for (LuaValue key : vals.keySet()) {
			LuaValue value = vals.get(key);
			
			buffer.append('[');
			buffer.append(key);
			buffer.append("] = ");
			buffer.append(value);
			buffer.append(", ");
		}
		
		buffer.append('}');
		return buffer.toString();
	}
}
